let
  defaultStableVersion = "1.87.0";
  defaultNightlyVersion = "2025-05-21";
in rec {
  # This map translates execution platforms to sensible targets that can
  # be built on such a platform. For instance, an x86_64-linux execution
  # platform can target aarch64-linux and musl targets, but not darwin.
  #
  # On the Bazel side each key maps to a dedicated toolchain capture the
  # cross-compile capabilities on the different exec platforms.
  nixSystemToRustTargets = {
    "aarch64-darwin" = [
      "aarch64-apple-darwin"
      "aarch64-unknown-linux-gnu"
      "aarch64-unknown-linux-musl"
      "x86_64-apple-darwin"
      "x86_64-unknown-linux-gnu"
      "x86_64-unknown-linux-musl"
    ];
    "aarch64-linux" = [
      "aarch64-unknown-linux-gnu"
      "aarch64-unknown-linux-musl"
      "x86_64-unknown-linux-gnu"
      "x86_64-unknown-linux-musl"
    ];
    "x86_64-darwin" = [
      "aarch64-apple-darwin"
      "aarch64-unknown-linux-gnu"
      "aarch64-unknown-linux-musl"
      "x86_64-apple-darwin"
      "x86_64-unknown-linux-gnu"
      "x86_64-unknown-linux-musl"
    ];
    "x86_64-linux" = [
      "aarch64-unknown-linux-gnu"
      "aarch64-unknown-linux-musl"
      "x86_64-unknown-linux-gnu"
      "x86_64-unknown-linux-musl"
    ];
  };

  # Changing execPkgs here allows creating custom cross-compilation toolchains:
  #
  #   custom-rust = rustConfig.mkRust {
  #     execPkgs = pkgs;
  #     channel = "stable";
  #     version = "1.83.0";  # You can override the version as well, but you'll
  #                          # need to run lre-rs afterwards to regenerate the
  #                          # Bazel-side rust toolchains.
  #   }
  #
  mkRust = {
    execPkgs,
    channel,
    extensions ? [],
  }: let
    version =
      if channel == "stable"
      then defaultStableVersion
      else defaultNightlyVersion;
    inherit (execPkgs.stdenv.buildPlatform) system;
    targets =
      nixSystemToRustTargets.${system}
      or (throw "Unsupported Nix exec platform: ${system}");
  in
    execPkgs.rust-bin.${channel}.${version}.default.override {
      inherit extensions targets;
    }
    // {
      # The version identifier generated by rust-bin can't be used by
      # `pkgs.rust-bin.${channel}.version`. This passthrough allows using the
      # version in classic rust imports like so:
      # `pkgs.rust-bin.${pkgs.lre.stable-rust.meta.version;}`
      meta = {inherit version;};
    };
}
